package com.pdd.mall.controller;

import com.pdd.mall.common.api.CommonResult;
import com.pdd.mall.dto.UpdatePasswordParam;
import com.pdd.mall.dto.UpdateUserInfoParam;
import com.pdd.mall.dto.UserLoginParam;
import com.pdd.mall.dto.UserRegisterParam;
import com.pdd.mall.entity.User;
import com.pdd.mall.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public CommonResult<User> register(@RequestBody @Valid UserRegisterParam param) {
        User user = userService.register(param);
        if (user == null) {
            return CommonResult.failed("用户名已存在");
        }
        return CommonResult.success(user);
    }

    @PostMapping("/login")
    public CommonResult<Map<String, String>> login(@RequestBody @Valid UserLoginParam param) {
        String token = userService.login(param);
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return CommonResult.success(tokenMap);
    }

    @GetMapping("/info")
    public CommonResult<User> getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserInfo(username);
        return CommonResult.success(user);
    }

    @PutMapping("/info")
    public CommonResult<User> updateUserInfo(@RequestBody @Valid UpdateUserInfoParam param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.updateUserInfo(username, param);
        return CommonResult.success(user);
    }

    @PostMapping("/logout")
    public CommonResult<String> logout() {
        return CommonResult.success(null);
    }

    @PutMapping("/password")
    public CommonResult<String> updatePassword(@RequestBody @Valid UpdatePasswordParam param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        boolean success = userService.updatePassword(username, param);
        if (success) {
            return CommonResult.success("密码修改成功");
        } else {
            return CommonResult.validateFailed("原密码不正确");
        }
    }
}
